package com.tgu.home_action.controller.admin;

import com.tgu.home_action.pojo.Client;
import com.tgu.home_action.pojo.Page;
import com.tgu.home_action.pojo.ResponseData;
import com.tgu.home_action.pojo.state.ResponseState;
import com.tgu.home_action.service.admin.AdminClientService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;

@Api(tags = "管理员的第三方接口管理")
@RestController
@RequestMapping("/admin/thirdParty")
public class AdminClientController {
    @Autowired
    private AdminClientService adminClientService;

    @ApiOperation("查询第三方应用")
    @PreAuthorize("hasAnyRole('admin','superAdmin','districtAdmin')")
    @GetMapping
    public ResponseData<Page<Client>> getClients(Client client) {
        return adminClientService.getClients(client);
    }

    @ApiOperation("添加第三方应用")
    @PreAuthorize("hasAnyRole('admin','superAdmin','districtAdmin')")
    @PostMapping
    public ResponseData<Client> addClient(@Validated(Client.insert.class) @RequestBody Client client) {
        try {
            return adminClientService.addClient(client);
        } catch (DuplicateKeyException e) {
            e.printStackTrace();
            return new ResponseData<>(ResponseState.USER_IS_EXIST.getMessage(), ResponseState.USER_IS_EXIST.getValue());
        }
    }

    @ApiOperation("修改第三方应用信息")
    @PreAuthorize("hasAnyRole('admin','superAdmin','districtAdmin')")
    @PutMapping
    public ResponseData<Client> updateClient(@Validated(Client.update.class) @RequestBody Client client) {
        try {
            return adminClientService.updateClient(client);
        } catch (DuplicateKeyException e) {
            e.printStackTrace();
            return new ResponseData<>(ResponseState.USER_IS_EXIST.getMessage(), ResponseState.USER_IS_EXIST.getValue());
        }
    }

    @ApiOperation("删除第三方应用")
    @PreAuthorize("hasAnyRole('admin','superAdmin','districtAdmin')")
    @DeleteMapping
    public ResponseData<Client> delClient(@RequestParam Integer clientId) {
        try {
            return adminClientService.delClient(clientId);
        } catch (DuplicateKeyException e) {
            e.printStackTrace();
            return new ResponseData<>(ResponseState.USER_IS_EXIST.getMessage(), ResponseState.USER_IS_EXIST.getValue());
        }
    }

}
